package com.insleton.admin.config;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.querydsl.sql.MySQLTemplates;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.SQLTemplates;
import com.querydsl.sql.mysql.MySQLQueryFactory;
import jakarta.persistence.EntityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class QueryDSLConfiguration {

    @Inject
    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }

    /**
     * SQL查询工厂，底层也是MySQL
     * @param dataSource 数据源
     * @return SQLQueryFactory
     */
    @Bean
    @Inject
    public SQLQueryFactory sqlQueryFactory(DataSource dataSource) {
        SQLTemplates sqlTemplates = MySQLTemplates.builder().printSchema().build();
        com.querydsl.sql.Configuration configuration = new com.querydsl.sql.Configuration(sqlTemplates);

        return new SQLQueryFactory(configuration, dataSource);
    }

    /**
     * MySQL查询工厂。和普通的查询工厂的区别是，多了几个MySQL SQL特殊的语法。
     *
     * @param dataSource 数据源
     * @return MySQLQueryFactory
     */
    @Bean
    @jakarta.inject.Inject
    public MySQLQueryFactory mySQLQueryFactory(DataSource dataSource) {
        SQLTemplates sqlTemplates = MySQLTemplates.builder().build();
        return new MySQLQueryFactory(sqlTemplates, () -> {
            try {
                return dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
